<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018/4/25
 * Time: 9:26
 */
namespace app\common\logic;

use think\Loader;

class TaobaoLogic
{

    public function __construct() {
        Loader::import('taobao\TopSdk', EXTEND_PATH);
        $c = new \TopClient;
        $c->appkey = '24798316';
        $c->secretKey = 'b60868c5ab3157899d9b0cfa05325669';
        $this->TopClient=$c;
        $this->UserId='17620797';
        $this->AdzoneId='237658530';
        $this->SiteId='42568708';
        $this->Token='7000210130535629810ba8f38d5c3a9a59c8965c64730b60e4ada3ac9babcd4f1affc80425137072';
        $this->QQ='2116177952';
        $this->Pid='mm_17620797_42568708_237658530';
        $this->post_url1='http://193.112.121.99/xiaocao/hightapi_wuquan.action';
        $this->post_url2='http://193.112.121.99/xiaocao/hightapi.action';
    }
/*
 * 地址转换
 *      $Request_url='http://193.112.121.99/xiaocao/hightapi_wuquan.action';
 *      $Request_url='http://193.112.121.99/xiaocao/hightapi.action';
 *      'token'=>'7000210130535629810ba8f38d5c3a9a59c8965c64730b60e4ada3ac9babcd4f1affc80425137072',
 */
    public function get_link($item_id){
//        $data=[
//            'token'=>$this->Token,
//            'item_id'=>$item_id,
//            'adzone_id'=>$this->AdzoneId,
//            'site_id'=>$this->SiteId,
//            'qq'=>$this->QQ
//
//        ];
//
//        $result_data=json_decode($this->curl_request($post_url,$data),true);
//     return $result_data;

        $url='https://uland.taobao.com/coupon/edetail?&pid='.$this->Pid.'&itemId='.$item_id.'&src=cd_cdll';
        return $url;
    }

    public function get_link2($item_id,$coupon_id){
        $url='https://uland.taobao.com/coupon/edetail?activityId='.$coupon_id.'&pid='.$this->Pid.'&itemId='.$item_id.'&src=cd_cdll';
        return $url;
    }

    /*
     * 淘口令生产
     */
    public function tpwd_creat($url='',$logo='',$desc=''){

        $req = new \TbkTpwdCreateRequest;
        $req->setUserId($this->UserId);
        $req->setText($desc);
        $req->setUrl($url);
        $req->setLogo($logo);
        $req->setExt("{}");
        $resp = $this->xml2array($this->TopClient->execute($req));

        return $resp['data']['model'];

    }

/*
 *   淘口令解析
 */
    public function tpwd_query($str){
        $req = new \WirelessShareTpwdQueryRequest;
        $req->setPasswordContent($str);
        $resp = $this->xml2array($this->TopClient->execute($req));

        return  $resp['url'];
    }

    /*
 *   taobao.tbk.dg.material.optional (通用物料搜索API（导购）)
 *   精准查找
 */
    public function optionalFinddetail($quere){

       if(has_tpwd($quere)){

          $tb_url= $this->tpwd_query($quere);

           $quere=$tb_url;
       }else{
           $data=[
               'has'=>0,
               'msg'=> '不支持关键字搜索',
               'code'=>0
           ];
           return $data;
       }

        $req = new \TbkDgMaterialOptionalRequest;
        $req->setQ($quere);
        $req->setAdzoneId($this->AdzoneId);

        $response=$this->xml2array($this->TopClient->execute($req));

        if($response['total_results']>0){//判断是否参加了淘宝客

            $goodinfo=$response['result_list']['map_data'];

            if(!empty($response['result_list']['map_data']['coupon_id'])){//判断是否存在优惠券

                 //粉丝福利购优惠券
                 $uland_url=$this->get_link2($goodinfo['num_iid'],$goodinfo['coupon_id']);
//                 $uland_url='https://s.click.taobao.com/t?e=m%3D2%26s%3D4qj2PNJbS1ocQipKwQzePOeEDrYVVa64pRe%2F8jaAHci5VBFTL4hn2Rlhopc0wH8RwSB8%2FImevIBupT2M%2B43KLPSlwknEhFyMzDGVmqWaZilSuMyhauT%2Bb7rd1liQ8fuBPeLoidblU0uT7cbDp%2FnQDT2l4PysJx%2FP';
                $goodinfo['uland_url']= $uland_url;
                 //淘口令
                $tpwd_creat= $this->tpwd_creat($uland_url,$goodinfo['pict_url'],$goodinfo['title'].'-'.$goodinfo['coupon_info']);
                $goodinfo['tpwd_creat']=$tpwd_creat;

                //适合满减优惠券
               $coupon_info= getCoupon($goodinfo['coupon_info']);

               if($coupon_info[0]<=$goodinfo['zk_final_price']){

                   $goodinfo['sub_final_coupon_price']=$goodinfo['zk_final_price']-$coupon_info[2];
                   $goodinfo['coupon_price']=$coupon_info[2];
               }
            }else{

                //粉丝福利购优惠券
                $taobao_url=$this->get_link($goodinfo['num_iid']);
//                 $taobao_url='https://uland.taobao.com/';

                $goodinfo['uland_url']= $taobao_url;
                //淘口令
                $goodinfo['tpwd_creat']=$this->tpwd_creat($taobao_url,$goodinfo['pict_url'],$goodinfo['title']);
            }
            $data=[
                'has'=>1,
                'good'=> $goodinfo,
                'code'=>'1'
            ];

        }else{
            $data=[
                'has'=>0,
                'msg'=> '当前没有查询到对应产品',
                'code'=>'1'
            ];

        }
        return $data;
    }

    /*
*   taobao.tbk.dg.material.optional (通用物料搜索API（导购）)
*   列表
*/
    public function optionalList($quere_array){

        $req = new \TbkDgMaterialOptionalRequest;
        $req->setStartDsr("10");
        $req->setPageSize("20");
        $req->setPageNo("1");
        $req->setPlatform("1");
        $req->setEndTkRate("1234");
        $req->setStartTkRate("1234");
        $req->setEndPrice("10");
        $req->setStartPrice("10");
        $req->setIsOverseas("false");
        $req->setIsTmall("false");
        $req->setSort("tk_rate_des");
        $req->setItemloc("杭州");
        $req->setCat("16,18");
        $req->setQ("男装");
        $req->setHasCoupon("true");
        $req->setAdzoneId("237658530");
        $response=$this->xml2array($this->TopClient->execute($req));
//        foreach ($response['tbk_dg_material_optional_response']['result_list']['map_data'] as )
        echo '<pre>';
        print_r($response);
    }

    //参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
    private function curl_request($url,$post='',$cookie='', $returnCookie=0){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if($returnCookie){
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie']  = substr($matches[1][0], 1);
            $info['content'] = $body;
            return $info;
        }else{
            return $data;
        }
    }



    public function xml2array($xmlobject){
        if ($xmlobject) {
            foreach ((array)$xmlobject as $k=>$v) {
                $data[$k] = !is_string($v) ? $this->xml2array($v) : $v;
            }
            return $data;
        }
    }
}